package com.funny.stock.trade.service;

import com.alibaba.fastjson.JSON;
import com.funny.stock.base.redis.RedisTool;
import com.funny.stock.base.vo.TradeType;
import com.funny.stock.data.vo.StockConstants;
import com.funny.stock.trade.vo.EmulateComposeVO;
import com.funny.stock.trade.vo.MonitorActionInfo;
import com.funny.stock.trade.vo.TradeActionInfo;
import com.funny.stock.user.service.RobotMsgService;
import com.funny.stock.user.service.SysUserService;
import com.funny.stock.user.service.email.MailService;
import com.funny.stock.user.vo.MailVO;
import com.funny.stock.user.vo.RobotMessage;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author pengl
 * @date 2020/11/22
 **/
@Component
public class StockMsgNotifyServiceImpl implements StockMsgNotifyService {
    public static final Logger logger = LoggerFactory.getLogger(StockMsgNotifyServiceImpl.class);

    @Autowired
    MailService mailService;

    @Autowired
    EmulateComposeService emulateComposeService;

    @Autowired
    SysUserService sysUserService;

    @Autowired
    RobotMsgService robotMsgService;

    @Autowired
    RedisTool redisTool;

    @Override
    public void onMonitorNotify(MonitorActionInfo monitorActionInfo) {
        logger.info("onMonitorNotify:{}", JSON.toJSON(monitorActionInfo));
        //{"code":"600048","planType":"t0","personId":3,"planId":2,"composeId":8,"realtimeStockData":{"symbol":"600048","code":"0600048","arrow":"↑","update":"2020/11/25 10:11:42","type":"SH","percent":0.010131,"high":16.95,"low":16.73,"price":16.95,"yestclose":16.78,"turnover":286952184,"askvol1":120700,"askvol2":61900,"askvol3":54400,"askvol4":130900,"askvol5":123300,"volume":17040924,"ask5":16.99,"bidvol1":54800,"ask2":16.96,"bidvol2":27300,"ask1":16.95,"bidvol3":33100,"ask4":16.98,"bid5":16.9,"bidvol4":1200,"ask3":16.97,"bidvol5":19100,"bid3":16.92,"name":"保利地产","bid4":16.91,"bid1":16.94,"bid2":16.93,"time":"2020/11/25 10:11:42","updown":0.17,"open":16.89,"status":0},"tradeType":"SELL"}
//        SysUserVO sysUserVO = sysUserService.findByUserId(monitorActionInfo.getPersonId());
//        if(sysUserVO == null) return;

        EmulateComposeVO composeVO = emulateComposeService.findByCreateIdAndId(monitorActionInfo.getPersonId(), monitorActionInfo.getComposeId());
        if(composeVO == null) return;

        String notifyText = createMonitorNotifyText(monitorActionInfo, composeVO);
        sendMailToUser(StockConstants.STOCK_SUBJECT, notifyText, monitorActionInfo.getPersonId());
        onNotifyRobotMsg(notifyText);
    }

    @Override
    public void onTradeNotify(TradeActionInfo tradeActionInfo) {
        logger.info("onTradeNotify:{}", JSON.toJSON(tradeActionInfo));
        EmulateComposeVO composeVO = emulateComposeService.findByCreateIdAndId(tradeActionInfo.getPersonId(), tradeActionInfo.getComposeId());
        if(composeVO == null) return;

        String notifyText = createTradeNotifyText(tradeActionInfo, composeVO);
        sendMailToUser(StockConstants.STOCK_SUBJECT, notifyText, tradeActionInfo.getPersonId());
        onNotifyRobotMsg(notifyText);
    }

    @Override
    public void onTradeNotifyFailMsg(TradeActionInfo tradeActionInfo,int code, String msg) {
        logger.info("onTradeNotifyFailMsg:{}", msg);
        String key = StockConstants.KEY_PRICE_NOT_ENOUGH_PREFIX + tradeActionInfo.getPersonId();

        if(code == StockConstants.PRICE_NOT_ENOUGH_CODE){
            String value = (String) redisTool.get(key);
            if("1".equals(value)){
                //已经通知过，默认key不过期不进行通知
                return;
            }

            redisTool.set(key, "1");
            redisTool.expire(key, 1, TimeUnit.HOURS);
        }

        String notifyText = createTradeNotifyText(tradeActionInfo, null);

        StringBuilder sb = new StringBuilder();
        sb.append("执行交易计划失败：\t");
        sb.append(msg);
        sb.append("\n\n");

        sb.append("交易信息如下：");
        sb.append(notifyText);

        sendMailToUser(StockConstants.STOCK_SUBJECT, sb.toString(), tradeActionInfo.getPersonId());
        onNotifyRobotMsg(sb.toString());
    }

    @Override
    public void onNotifyRobotMsg(String msg) {
        RobotMessage robotMessage = new RobotMessage();
        robotMessage.setContent(msg);
        robotMsgService.sendMessage(robotMessage);
    }

    private void sendMailToUser(String subject,String text,Long userInfoId){
        MailVO mailVO = new MailVO();
        mailVO.setText(text);
        mailVO.setSubject(StringUtils.isEmpty(subject) ? "" : subject);
        mailService.sendMailToUser(mailVO, userInfoId);
    }

    private String createMonitorNotifyText(MonitorActionInfo actionInfo,EmulateComposeVO composeVO) {
        StringBuilder sb = new StringBuilder();
        if(composeVO != null){
            sb.append("股价监控触发提醒：");
            sb.append("\n\n");

            sb.append("组合");
            sb.append(composeVO.getName());

            sb.append("刚刚触发了一笔");
            sb.append(actionInfo.getTradeType() == TradeType.BUY ? "跌幅" : "涨幅");
            sb.append("提醒");
            sb.append("\n\n");
        }

        sb.append("股票名称:\t");
        sb.append(actionInfo.getRealtimeStockData().getName());
        sb.append("(");
        sb.append(actionInfo.getRealtimeStockData().getSymbol());
        sb.append(")");
        sb.append("\n");

        String tradePlanType = StockConstants.STOCK_STRATEGY_GRID.equals(actionInfo.getPlanType())? "网格交易": "T0日内交易";
        sb.append("交易类型:\t");
        sb.append(tradePlanType);
        sb.append("\n");
//        sb.append(actionInfo.getTradeType() == TradeType.BUY ? "跌幅" : "涨幅");
//        sb.append(":\t");
//        sb.append(actionInfo.getRealtimeStockData().getPercent());
//        sb.append("(");
//        sb.append(DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm"));
//        sb.append(")");
//        sb.append("\n");

        sb.append("当前价格:\t");
        sb.append(actionInfo.getRealtimeStockData().getPrice());
        sb.append("(");
        BigDecimal percent = BigDecimal.valueOf(actionInfo.getRealtimeStockData().getPercent()).multiply(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
        sb.append(percent);
        sb.append("%)");
        sb.append("\n");

        sb.append("触发条件:\t");
        sb.append("日");
        sb.append(actionInfo.getTradeType() == TradeType.BUY ? "跌幅" : "涨幅");
        sb.append("达");
        sb.append(actionInfo.getTradeType() == TradeType.BUY ? actionInfo.getPlanDecreasePer() : actionInfo.getPlanIncreasePer());
        sb.append("%\n");


        sb.append("备注:\t");
        sb.append("更多详情，请登录系统进一步了解");
//        sb.append(JSON.toJSONString(actionInfo));
        sb.append("\n");

        return sb.toString();
    }

    private String createTradeNotifyText(TradeActionInfo actionInfo,EmulateComposeVO composeVO){
        StringBuilder sb = new StringBuilder();
        if(composeVO != null) {
            sb.append("交易完成提醒：");
            sb.append("\n\n");
            sb.append("组合");
            sb.append(composeVO.getName());
            sb.append("刚刚完成了一笔");
            sb.append(actionInfo.getTradeType() == TradeType.BUY ? "低吸" : "高抛");
            sb.append("操作");
            sb.append("\n\n");
        }

        sb.append("股票名称:\t");
        sb.append(actionInfo.getRealtimeStockData().getName());
        sb.append("(");
        sb.append(actionInfo.getRealtimeStockData().getSymbol());
        sb.append(")");
        sb.append("\n");

        boolean isGridPlan = StockConstants.STOCK_STRATEGY_GRID.equals(actionInfo.getPlanType());

        String tradePlanType = isGridPlan? "网格交易": "T0日内交易";
        sb.append("交易类型:\t");
        sb.append(tradePlanType);
        sb.append(actionInfo.getTradeType() == TradeType.BUY ? "低吸" : "高抛");
        sb.append("(");
        sb.append(DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm"));
        sb.append(")");
        sb.append("\n");

        if(!isGridPlan){
            sb.append("触发条件:\t");
            sb.append("日");
            sb.append(actionInfo.getTradeType() == TradeType.BUY ? "跌幅" : "涨幅");
            sb.append("达");
            sb.append(actionInfo.getTradeType() == TradeType.BUY ? actionInfo.getPlanDecreasePer() : actionInfo.getPlanIncreasePer());
            sb.append("%\n");
        }

        sb.append("成交数量:\t");
        sb.append(actionInfo.getTradeNumber());
        sb.append("\n");

        sb.append("成交均价:\t");
        sb.append(actionInfo.getRealtimeStockData().getPrice());
        sb.append("(");
        BigDecimal percent = BigDecimal.valueOf(actionInfo.getRealtimeStockData().getPercent()).multiply(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
        sb.append(percent);
        sb.append("%)");
        sb.append("\n");

        sb.append("兑现收益:\t");
        sb.append(actionInfo.getMatchProfit() == null ? "--" : actionInfo.getMatchProfit().toString());
        sb.append("\n");

        sb.append("备注:\t");
        sb.append("更多详情，请登录系统进一步了解");
        sb.append("\n");

        return sb.toString();
    }

}
